<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 3] 3.2 Reference Types</TITLE>
<META NAME="author" CONTENT="Mark Grand">
<META NAME="date" CONTENT="Thu Jul 31 13:07:31 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="java">
<META NAME="title" CONTENT="Java Language Reference">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Java Language Reference" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch03_01.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 3<br>Data Types</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch04_01.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="JLR2-CH-3-SECT-2">3.2 Reference Types</A></h2>

<P CLASS=para>
<A NAME="CH03.REF"></A>Java is an object-oriented language. An object is a collection
of variables and associated methods that is described by a class.
The concepts in this section that relate to objects
are discussed in detail in <A HREF="ch05_03.htm#JLR2-CH-5-SECT-3">Object-Orientation Java Style</A>.

<P CLASS=para>
The name of a class can be used as a type, so you can declare
an object-type variable or specify that a method returns an object.
If you declare a variable using the name of a class for its type,
that variable can contain a <I CLASS=emphasis>reference</I>
to an object of that class. Such a variable does not contain
an actual object, but rather a reference to the class instance,
or object, the variable refers to. Because using a class name as
a type declares a reference to an object, such types are called
<I CLASS=emphasis>reference types</I>. Java also allows the use of
an interface name to specify a reference type. In addition, array
types in Java are reference types because Java treats arrays as
objects.

<P CLASS=para>
The two main characteristics of objects in Java are that:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>Objects are always dynamically allocated. The lifetime of
the storage occupied by an object is determined by the program's
logic, not by the lifetime of a procedure call or the boundaries
of a block. The lifetime of the storage occupied by an object refers
to the span of time that begins when the object is created and ends
at the earliest time it can be freed by the garbage collector.

<P>
<li CLASS=listitem>Objects are not contained by variables. Instead, a variable
contains a reference to an object. A reference is similar to what
is called a pointer in other languages. If there are two variables
of the same reference type and one variable is assigned
to the other, both variables refer to the same object. If the information
in that object is changed, the change is visible through both variables.

<P>
</UL>
<P CLASS=para>
Java references are very similar to pointers in C/C++, but
they are not at all related to the C++ notion
of a reference. The main difference between Java references and
C++ pointers is that Java does not allow any arithmetic to be done
with references. This, coupled with Java's lack of any way to explicitly
deallocate the storage used by reference type values, guarantees
that a reference can never point to an illegal address.

<P CLASS=para>
The formal definition of a reference type is:


<p>
<img align=middle src="./figs/jlr0306.gif" alt="[Graphic: Figure from the text]" width=424 height=77 border=0>

<P CLASS=para>
It is possible to cause
a reference variable to contain a reference to nothing by assigning
the special value represented by the keyword <tt CLASS=literal>null</tt>
to the variable. The value <tt CLASS=literal>null</tt> can be assigned
to any reference variable without a type cast.

<P CLASS=para>
Java does not allow reference types to be cast to primitive
data types or primitive data types to be type cast to reference
types. In particular, unlike C/C++, there is no conversion between
integer values and references.

<P CLASS=para>
The only operation that Java provides for reference-type variables
is the ability to fetch the referenced object. However, Java does
not provide an operator to fetch the object referenced by a reference
variable. Instead, the object fetch operation is performed implicitly
by the following operations:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>A field expression that accesses a variable or method of a
class or interface object

<P>
<li CLASS=listitem>A field expression that accesses an element of an array object

<P>
<li CLASS=listitem>A type comparison operation that uses the <tt CLASS=literal>instanceof</tt>
operator

<P>
</UL>
<P CLASS=para>
<b>References</b>
<A HREF="ch03_02.htm#JLR2-CH-3-SECT-2.3">Array Types</A>;
<I CLASS=emphasis>ClassOrInterfaceName</I> 4.1.6;
<A HREF="ch03_02.htm#JLR2-CH-3-SECT-2.1">Class Types</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1.6">Field Expressions</A>;
<A HREF="ch03_02.htm#JLR2-CH-3-SECT-2.2">Interface Types</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1.3">null</A>;
<A HREF="ch05_03.htm#JLR2-CH-5-SECT-3">Object-Orientation Java Style</A>;
<A HREF="ch03_01.htm#JLR2-CH-3-SECT-1">Primitive Types</A>;
<A HREF="ch04_08.htm#JLR2-CH-4-SECT-8.5">The instanceof Operator</A>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-3-SECT-2.1">Class Types</A></h3>

<P CLASS=para>
<A NAME="CH03.CLASS"></A>The name of a class can be used to specify the type of a
reference. If a variable is declared as a class type, the variable either
contains <tt CLASS=literal>null</tt> or a reference to an object of
that class or a subclass of that class. It is not allowed to contain
any other kinds of values. For example:

<DIV CLASS=screen>
<P>
<PRE>
class Shape { ... }
class Triangle extends Shape { ... }
...
Shape s;
Triangle t;
...
s = t;
</PRE>
</DIV>

<P CLASS=para>
This example declares a class called <tt CLASS=literal>Shape</tt>
and a subclass of <tt CLASS=literal>Shape</tt> called <tt CLASS=literal>Triangle</tt>.
The code later declares a reference variable called <tt CLASS=literal>s</tt>
that can contain a reference to a <tt CLASS=literal>Shape</tt> object
and another variable
called <tt CLASS=literal>t</tt> that can contain a reference to a <tt CLASS=literal>Triangle</tt>
object. The value of <tt CLASS=literal>s</tt> can be assigned to the
value of <tt CLASS=literal>t</tt> because an object is not only an instance
of its declared class, but also an instance of every superclass
of its declared class. Since instances of the <tt CLASS=literal>Triangle</tt>
class are also instances of its superclass <tt CLASS=literal>Shape</tt>,
the Java compiler has no problem with <tt CLASS=literal>s = t</tt>.

<P CLASS=para>
However, saying <tt CLASS=literal>t = s</tt> generates an error
message from the compiler. Java does not allow a reference variable
declared as a class type to contain a reference to a superclass
of the declared class. The assignment <tt CLASS=literal>t = s</tt> is
illegal because <tt CLASS=literal>Shape</tt> is a superclass of <tt CLASS=literal>Triangle</tt>. The assignment can be accomplished if <tt CLASS=literal>s</tt>
is first cast to a reference to <tt CLASS=literal>Triangle</tt>:

<DIV CLASS=screen>
<P>
<PRE>
t = (Triangle)s;
</PRE>
</DIV>

<P CLASS=para>
The cast operation ensures that the object referenced
by <tt CLASS=literal>s</tt> is a class type that is either
<tt CLASS=literal>Triangle</tt>
or a descendant of <tt CLASS=literal>Triangle</tt>. When you cast an
object reference to a subclass of the reference type, you are saying
that you want to treat the object being referenced as an instance
of the specified subclass. If the compiler cannot determine whether
the argument of a cast will be of the required type, the compiler
generates runtime code that ensures that the argument really is
an instance of the specified subclass. At runtime, if the class
of the object being referenced is not an instance of the specified
subclass, a <tt CLASS=literal>ClassCastException</tt> is thrown.

<P CLASS=para>
<b>References</b>
<A HREF="ch04_04.htm#JLR2-CH-4-SECT-4.5">Casts</A>;
<A HREF="ch05_03.htm#JLR2-CH-5-SECT-3.1">Classes</A>;
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4">Class Declarations</A>;
<A HREF="ch04_02.htm#JLR2-CH-4-SECT-2.1">Object Allocation Expressions</A>;
<A HREF="ch09_04.htm#JLR2-CH-9-SECT-4.1.1">Runtime exceptions</A>

<DIV CLASS=sect3>
<h4 CLASS=sect3><A CLASS="TITLE" NAME="JLR2-CH-3-SECT-2.1.1">Specially supported classes</A></h4>

<P CLASS=para>
Java provides special support for the <tt CLASS=literal>String</tt>
and <tt CLASS=literal>StringBuffer</tt> classes. All string literals
are compiled into <tt CLASS=literal>String</tt> objects. The result
of a string concatenation operation is a <tt CLASS=literal>String</tt>
object. An intermediate <tt CLASS=literal>StringBuffer</tt> object is
used to compute the result of a concatenation operation. Because
operations on strings are generally based on the length of the string,
Java does not automatically supply a NUL character (<tt CLASS=literal>\u0000</tt>)
at the end of a string literal. For the same reason, it is not customary
for Java programs to put a NUL character at the end of a string.

<P CLASS=para>
Java also provides special support for the <tt CLASS=literal>Object</tt>
class. This class is the ultimate superclass of all other classes
in Java. If a class is declared without its superclass being specified,
the language automatically specifies <tt CLASS=literal>Object</tt> as
its superclass.

<P CLASS=para>
The <tt CLASS=literal>throw</tt> statement in Java is special,
in that it requires the use of a <tt CLASS=literal>Throwable</tt> object.

<P CLASS=para>
<b>References</b>
<A HREF="ch10_14.htm">Object</A>;
<A HREF="ch10_20.htm">String</A>;
<A HREF="ch10_21.htm">StringBuffer</A>;
<A HREF="ch04_06.htm#JLR2-CH-4-SECT-6.3">String Concatenation Operator +</A>;
<A HREF="ch02_02.htm#JLR2-CH-2-SECT-2.3.5">String literals</A>;
<A HREF="ch06_11.htm#JLR2-CH-6-SECT-11">The throw Statement</A>;
<A HREF="ch10_25.htm">Throwable</A>

</DIV>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-3-SECT-2.2">Interface Types</A></h3>

<P CLASS=para>
The name of an interface can be used to specify the type of
a reference. A reference variable declared using an interface name
as its type can only reference instances of classes that implement
that interface. For example, Java provides an interface called
<tt CLASS=literal>Runnable</tt>.
Java also provides a class called <tt CLASS=literal>Thread</tt> that
implements <tt CLASS=literal>Runnable</tt>. This means that the following
assignment is allowed:

<DIV CLASS=screen>
<P>
<PRE>
Runnable r;
r = new Thread();
</PRE>
</DIV>

<P CLASS=para>
The Java compiler does not allow a value to be assigned to
a variable declared using an interface type unless the compiler
can be sure that the object referenced by the value implements the
specified interface. Casting a reference variable to an interface
type allows the variable to be assigned to that interface type,
because the cast operation provides its own guarantee that the object
implements the specified interface. Unless the compiler is able
to determine the actual class of the object that will be referenced
at runtime, the cast produces code that verifies at runtime that
the object being cast really does implement the specified interface.
At runtime, if the object being cast does not implement the required
interface, a <tt CLASS=literal>ClassCastException</tt> is thrown.

<P CLASS=para>
<b>References</b>
<A HREF="ch04_04.htm#JLR2-CH-4-SECT-4.5">Casts</A>;
<A HREF="ch05_03.htm#JLR2-CH-5-SECT-3.6">Interfaces</A>;
<A HREF="ch05_05.htm#JLR2-CH-5-SECT-5">Interface Declarations</A>;
<A HREF="ch04_02.htm#JLR2-CH-4-SECT-2.1">Object Allocation Expressions</A>;
<A HREF="ch09_04.htm#JLR2-CH-9-SECT-4.1.1">Runtime exceptions</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-3-SECT-2.3">Array Types</A></h3>

<P CLASS=para>
<A NAME="CH03.ARRAY"></A>An array is a special kind of
object that contains values called <I CLASS=emphasis>elements</I>.
Array elements are similar to variables in that they contain values
that can be used in expressions and set by assignment operations.
Elements differ from variables, however, in that they do not have
names. Instead, they are identified by non-negative integers. The
elements in an array are identified by a contiguous range of integers
from 0 to one less than the number of elements in the array. The
elements of an array must all contain the same type of value; the
type of the array is specified when the array is created.

<P CLASS=para>
An array-type variable is declared as follows:

<DIV CLASS=screen>
<P>
<PRE>
int [] a;
</PRE>
</DIV>

<P CLASS=para>
This declaration specifies that the variable <tt CLASS=literal>a</tt>
refers to an array of <tt CLASS=literal>int</tt> values. Java actually
allows two styles of array declarations: the one shown above and
a style that is more like that used in C/C++. In other words, you
can put the square brackets after the variable name instead of after
the type:

<DIV CLASS=screen>
<P>
<PRE>
int a[];
</PRE>
</DIV>

<P CLASS=para>
Technically, all arrays in Java are one-dimensional. However,
Java does allow you to declare an array of arrays, which is a more
flexible data structure than a multi-dimensional array. The additional
flexibility comes from the fact that the arrays in an array of arrays
do not have to be the same length. Because arrays of arrays are
typically used to represent multi-dimensional arrays, this book
refers to them as multi-dimensional arrays, even though that is
not precisely correct.

<P CLASS=para>
A multi-dimensional array is declared using multiple pairs
of square brackets, as in the following examples:

<DIV CLASS=screen>
<P>
<PRE>
int [][] d2;       // Refers to a 2-dimensional array
int [][][] d3;     // Refers to a 3-dimensional array
</PRE>
</DIV>

<P CLASS=para>
When you declare a variable to refer to a multi-dimensional
array, the number of dimensions in the array is determined by the
number of pairs of square brackets. Whether the brackets follow
the type name or the variable name is not important. Thus, the above
variables could have been declared like this:

<DIV CLASS=screen>
<P>
<PRE>
int [] d2[],       // Refers to a 2-dimensional array
       d3[][];     // Refers to a 3-dimensional array
</PRE>
</DIV>

<P CLASS=para>
The actual length of each dimension of an array object is
specified when the array object is created, not when the array variable
is declared. An array object is not created
at the same time that an array variable is declared. An array object
is created with the <tt CLASS=literal>new</tt> operator. Here are some
examples:

<DIV CLASS=screen>
<P>
<PRE>
int j[] = new int[10];        // An array of 10 ints
int k[][] = new float[3][4];  // An array of 3 arrays of 4 floats
</PRE>
</DIV>

<P CLASS=para>
The arrays contained in an array of arrays can also be of
different lengths:

<DIV CLASS=screen>
<P>
<PRE>
int a[][] = new int [3][];
a[0] = new int [5];
a[1] = new int [6];
a[2] = new int [7];
</PRE>
</DIV>

<P CLASS=para>
Although the first <tt CLASS=literal>new</tt> operator is creating a
two-dimensional array, only the length of one dimension is specified.
In this case, just the array of arrays is created. The subarrays are
created by the subsequent <tt CLASS=literal>new</tt> operators.

<P CLASS=para>
The expression used to specify the length of an array does
not have to be a constant. Consider the following example:

<DIV CLASS=screen>
<P>
<PRE>
int[] countArray(int n){
    int[] a = new int[n];
    for (int i=0; i&lt;n; i++) {
        a[i]=i+1;
    }
    return a;
}
</PRE>
</DIV>

<P CLASS=para>
The number of elements in an array object is fixed at the
time that the array object is created and cannot be changed.[2]
Every array object has a public variable called <tt CLASS=literal>length</tt>
that contains the number of elements in the array. The variable
<tt CLASS=literal>length</tt> is <tt CLASS=literal>final</tt>, which means
that its value cannot be changed by assignment.

<blockquote class=footnote>
<P CLASS=para>[2] 
The
standard class <tt CLASS=literal>java.util.Vector</tt>
implements an array-like object with a length that can be changed.
</blockquote>
<P CLASS=para>
The Java notion of arrays is fundamentally different than
that of C/C++. Subscripting a Java array does not imply pointer
arithmetic, so there is no danger of an out-of-range index accessing
memory that shouldn't be accessed. Array objects in Java detect
out-of-range subscripts; when they do they throw an <tt CLASS=literal>ArrayIndexOutOfBoundsException</tt>.
And unlike C/C++, arrays of type <tt CLASS=literal>char</tt> are not
strings in Java. Instead, Java uses the <tt CLASS=literal>String</tt>
class to support strings.

<P CLASS=para>
Although array objects are reference types, array objects
are different from other kinds of objects. The <tt CLASS=literal>Object</tt>
class is the parent class of all array objects, but array objects
do not really belong to a class of their own. An array object inherits
all of the variables and methods of the <tt CLASS=literal>Object</tt> 
class. Every array
also defines the variable <tt CLASS=literal>length</tt>, but there is
no class declaration for an array type.

<P CLASS=para>
<b>References</b>
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.1.4">Variable initializers</A>;
<A HREF="ch04_02.htm#JLR2-CH-4-SECT-2.2">Array Allocation Expressions</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1.7">Index Expressions</A>;
<A HREF="ch10_14.htm">Object</A>;
<A HREF="ch10_20.htm">String</A>

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch03_01.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch04_01.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Primitive Types</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Expressions</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
